/**
 * @author kan
 */
var mainTabs;

$(function () {
	var layout = $("body").layout({ 
		resizerClass: "ui-widget-header",
        togglerClass: "ui-state-default",
        west__size: 200,
        resizable: true,
		useStateCookie: true
	});
	
	$("#menu").accordion();
	
	$("#menu td").hover(function() {
		$(this).addClass("hovered");
	}, function() {
		$(this).removeClass("hovered");
	}).click(function () {
		$("#menu .selected").removeClass("selected");
		$(this).addClass("selected");
		
		var parts = this.id.split("-");
		parts.pop();
        var url = parts.join("_");		
		var tabId = "#tab-" + url;
		if ($(tabId).html()) {
			mainTabs.tabs("select", tabId);
		} else {
			mainTabs.tabs("add", tabId, $(this).html());
			$(tabId, "#main-tabs").load(url);
		}
	});
	
	var openedTabsStr = $.cookie("openedTabs");
	var openedTabs = [];
	if (openedTabsStr) {
	  openedTabs = JSON.parse(openedTabsStr);
	}
	mainTabs = $("#main-tabs", "#center-pane").tabs({
      add: function(e, ui) {
  			// append close thingy
  			$(ui.tab).parents("li:first").append('<span class="ui-tabs-close ui-icon ui-icon-close" title="Close Tab"></span>')
  				.find("span.ui-tabs-close").click(function(){
    				mainTabs.tabs("remove", $("li", mainTabs).index($(this).parents("li:first")[0]));
  			});

			 // select just added tab
		  	mainTabs.tabs("select", "#" + ui.panel.id);
            var found = false;
            $.each(openedTabs, function() {
                if (this.id == ui.panel.id) {
                    found = true;
                    return false;
                }
            });
            if (!found) {
                openedTabs.push({
                    id: ui.panel.id,
                    label: ui.tab.text
                });
            }
		  	$.cookie("openedTabs", JSON.stringify(openedTabs));
		  },
		  remove: function(e, ui) {
		      for (var i = 0; i < openedTabs.length; i++) {
                  if (openedTabs[i].id == ui.panel.id) {
                      break;
                  }
		      }
		      if (i < openedTabs.length) {
                  openedTabs.splice(i, 1);
                     $.cookie("openedTabs", JSON.stringify(openedTabs));
		          }
		  }
	});
	
	$.each(openedTabs, function() {
        mainTabs.tabs("add", "#" + this.id, this.label);
        $("#" + this.id, "#main-tabs").load(this.id.substring("tab-".length));
	});
	
	if ($.cookie("activeMenuItem")) {
	    console.debug("#" + $.cookie("activeMenuItem"));
	    window.setTimeout(function() {
            $("#" + $.cookie("activeMenuItem")).click();
	    }, 500);
	}
	
	$(window).unload(function() {
        $.cookie("activeMenuItem", $(".selected", "#menu").attr("id"));
	});
});